/**
 * Created by nico on 2016/2/26.
 */
//全局变量
var PAGE_SIZE = 2 ;
//获取页数
function getPage(count){
    var allPage = count / PAGE_SIZE  ;
    if(count%PAGE_SIZE === 0){
        allPage = count / PAGE_SIZE ;
    }else{
        allPage = (count / PAGE_SIZE) + 1 ;
    }
    return allPage ;
}
//任务首页
app.controller('TaskHomeCtrl',['$scope','$state','$stateParams','BaseFactory','$User','$rootScope','$cordovaBarcodeScanner',
    function($scope,$state,$stateParams,BaseFactory,$User,$rootScope,$cordovaBarcodeScanner){

        $rootScope.$on('$stateChangeStart', function(event,toState,fromState){
            if(toState.name === 'tab.tasks'){
                $scope.init() ;
                $scope.initwait();
            }
        });
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init() ;
            $scope.initwait();
        };
        //用户id
        $scope.taskHome = {inExpress:0,finishExpress:0,backGoods:0,changeGoods:0, bookTime:0,reject:0};
        $scope.wait = {waittake:0,dsd:0,sd:0};

        var uid = $User.get('id') ;
        $scope.init =function(){
            //获取任务首页的各个分类的数量
            BaseFactory.taskHome(uid).then(function(data){
                var inExpress = data[0].zp ;   //在派送
                var finishExpress = data[0].ywc ; //已完成
                var backGoods = data[0].th ;   //退货
                var changeGoods = data[0].hh ;   //换货
                var bookTime = data[0].yy ;   //预约
                var reject = data[0].js || 0;   //拒收
                $scope.taskHome = {inExpress:inExpress,finishExpress:finishExpress,backGoods:backGoods,changeGoods:changeGoods, bookTime:bookTime,reject:reject};
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }

        $scope.initwait =function(){
            BaseFactory.taskWaitTake(uid).then(function(data){
                var waittake = data[0].waittake ||0;
                var dsd = data[0].dsd ||0;
                var sd = data[0].sd ||0;
                $scope.wait = {waittake:waittake,dsd:dsd,sd:sd};
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }

        //展示首页
        $scope.init();

        //展示待领取
        $scope.initwait();

        //搜索
        $scope.searchTask = function(code){
            //根据输入的订单编号搜索
            $state.go('tab.search',{code:code}) ;
        };
        //在派送
        $scope.inExpress = function(){
            //显示所有状态为7000或者8000的订单
            $state.go('tab.inExpress') ;
        };
        //退货，跳转到退货类别
        $scope.backGoods = function(){
            //显示所有状态为7000或者8000的订单并且type为11
            $state.go('tab.backGoods') ;
        };
        //换货，跳转到换货类别
        $scope.exchangeGoods = function(){
            //显示所有状态为7000或者8000的订单并且type为12
            $state.go('tab.exchangeGoods') ;
        };

        //已完成，跳转到已完成列表
        $scope.hasFinished = function(){
            //显示所有状态为9000，9999的订单并且is_account=1
            $state.go('tab.hasFinished') ;
        };
        //预约，跳转到预约列表
        $scope.booktime = function(){
            //显示所有状态为9000，9999的订单并且is_account=1
            $state.go('tab.booktime') ;
        };
        //拒收，跳转到拒收列表
        $scope.reject = function(){
            //显示所有状态为9000，9999的订单并且is_account=1
            $state.go('tab.reject') ;
        };
        //跳转到待领单列表
        $scope.waittakelist = function(){
            $state.go('tab.waittake') ;
        };

        //扫码领单
        $scope.barscan = function(){
            $cordovaBarcodeScanner
                .scan()
                .then(function(barcodeData) {
                    var cancelled = barcodeData.cancelled;
                    var result = JSON.parse(barcodeData.text);
                    if(!cancelled){
                        var oid = result.OID;
                        if(oid){
                            BaseFactory.taskDetail(uid,oid).then(function(data){
                                if(data.id){
                                    $state.go('tab.taskDetail',{code:oid}) ;
                                }else{
                                    alert('该订单已被他人领取，无法定位');
                                }
                            }).catch(function(err){
                                alert('没有获取到您搜索的订单详情');
                            })
                        }else{
                            alert('没有获取到oid');
                        }
                    }else{
                        alert('扫描异常或退出扫描');
                    }
                }, function(error) {
                    // An error occurred
                    alert('扫描异常或退出扫描');
                });
        };
    }
]);
//搜索页面
app.controller('SearchCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        var search_code = $stateParams.code ;
        $scope.loadmore = {more:true};
        var page = 1 ;
        var uid = $User.get('id') ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        $scope.tasks = [] ;
        $scope.init =function(page){
            //获取搜索到的全部记录
            BaseFactory.searchTask(uid,search_code,page,PAGE_SIZE).then(function(data){
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        };
        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        };
        //展示首页
        $scope.init(page);
        $scope.bookTime = function(event,code,task){

            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });

            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code,new Date($scope.data.booktime).getTime()).then(function(data){
                                    if(data.code === 0){
                                        alert('预约完成');
                                        $scope.tasks.splice(task,1);
                                    }else{
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            }).then(function(res){
                $scope.data.booktime = new Date();
            })
        };
        //完成派送
        $scope.finishExpress = function(event,code,task){
            //完成派送，记录完成派送时间，更新状态status=9000
            if(!confirm("确认完成派送？")){
                return ;
            }
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.finishExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    alert('派送完成');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                alert(err);
            });
        };
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };
        //拒收
        $scope.reject = function(event,code,task){
            //用户拒收，修改订单状态为拒收status=9001
            //alert('用户拒收，该功能尚未开发');
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            var dialog = prompt('确认客户拒收？');
            if(dialog){
                BaseFactory.rejectExpress(uid,code,dialog).then(function(data){
                    if(data.code === 0){
                        alert('更新成功');
                        $scope.tasks.splice(task,1);
                    }else{
                        alert(data.msg);
                    }
                }).catch(function(err){
                    //console.log(err)
                    alert('更新失败，请刷新页面后重试');
                });
                //alert('客户确认拒收'+dialog);
            }else{
                //alert('客户取消拒收'+dialog);
            }
        }
    }
]);
//在派送页面
app.controller('InExpressCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$timeout','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$timeout,$User,$cordovaGeolocation){
        $scope.loadmore = {more:true};
        $scope.tasks = [] ;
        var page = 1 ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        var uid = $User.get('id') ;
        $scope.inExpress = {show_book_date:0,book_date:''}
        $scope.init =function(page){
            //获取任务首页的各个分类的数量
            BaseFactory.inExpress(uid,page, PAGE_SIZE).then(function(data){
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init(page);

        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        }
        $scope.bookTime = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code,$scope.data.booktime.getTime()).then(function(data){
                                    if(data.code === 0){
                                        alert('预约完成');
                                        $scope.tasks.splice(task,1);
                                    }else{
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            })
        }
        //完成派送
        $scope.finishExpress = function(event,code,task){
            //完成派送，记录完成派送时间，更新状态status=9000
            if(!confirm("确认完成派送？")){
                return ;
            }
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.finishExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    //alert('派送完成');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                alert(err);
            });
        };
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };
        //拒收
        $scope.reject = function(event,code,task){
            //用户拒收，修改订单状态为拒收status=9001
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            var dialog = prompt('确认客户拒收？');
            if(dialog){
                BaseFactory.rejectExpress(uid,code,dialog).then(function(data){
                    if(data.code === 0){
                        alert('更新成功');
                        $scope.tasks.splice(task,1);
                    }else{
                        alert(data.msg);
                    }
                }).catch(function(err){
                    //console.log(err)
                    alert('更新失败，请刷新页面后重试');
                });
                //alert('客户确认拒收'+dialog);
            }else{
                //alert('客户取消拒收'+dialog);
            }

        }

    }
]);
//展示商品详情页
app.controller('TaskDetailCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init() ;
        };
        var code = $stateParams.code ;
        //用户id
        var uid = $User.get('id') ;
        var task = {}
        $scope.init =function(){
            //获取任务首页的各个分类的数量
            BaseFactory.taskDetail(uid,code).then(function(data){
                $scope.task = data ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init();

        $scope.bookTime = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code,$scope.data.booktime.getTime()).then(function(data){
                                    if(data.code === 0){
                                        alert('预约完成');
                                        //$scope.tasks.splice(task,1);
                                        $state.go('tab.tasks') ;
                                    }else{
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            })
        }
        //完成派送
        $scope.finishExpress = function(event,code,task){
            //完成派送，记录完成派送时间，更新状态status=9000
            if(!confirm("确认完成派送？")){
                return ;
            }
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.finishExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    //alert('派送完成');
                    //完成派送后跳转到在派送任务列表，并刷新页面
                    $state.go('tab.inExpress') ;
                    //$scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                console.log(err)
            });
        };
        //拒收
        $scope.reject = function(event,code){
            //用户拒收，修改订单状态为拒收status=9001
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            var dialog = prompt('确认客户拒收？');
            if(dialog){
                BaseFactory.rejectExpress(uid,code,dialog).then(function(data){
                    if(data.code === 0){
                        alert('更新成功');
                        //$scope.tasks.splice(task,1);
                    }else{
                        alert(data.msg);
                    }
                }).catch(function(err){
                    //console.log(err)
                    alert('更新失败，请刷新页面后重试');
                });
                //alert('客户确认拒收'+dialog);
            }else{
                //alert('客户取消拒收'+dialog);
            }
        }
    }
]);
//退货页面
app.controller('BackGoodsCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        $scope.loadmore = {more:true};
        $scope.tasks = [] ;
        var page = 1 ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        var uid = $User.get('id');
        $scope.init =function(page){
            //获取任务首页的各个分类的数量
            BaseFactory.backGoods(uid,page,PAGE_SIZE).then(function(data){
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init(page);
        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        }
        $scope.bookTime = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code,$scope.data.booktime.getTime()).then(function(data){
                                    if(data.code === 0){
                                        alert('预约完成');
                                        $scope.tasks.splice(task,1);
                                    }else{
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            })
        }
        //完成派送
        $scope.finishExpress = function(event,code,task){
            //完成派送，记录完成派送时间，更新状态status=9000
            if(!confirm("确认完成派送？")){
                return ;
            }
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.finishExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    //alert('派送完成');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                console.log(err)
            });
        };
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };
        //拒收
        $scope.reject = function(event,code,task){
            //用户拒收，修改订单状态为拒收status=9001
            alert('用户拒收，该功能尚未开发');
            /*var dialog = prompt('确认客户拒收？');
            if(dialog){
                BaseFactory.rejectExpress(uid,code,dialog).then(function(data){
                    if(data.code === 0){
                        alert('更新成功');
                        $scope.tasks.splice(task,1);
                    }else{
                        alert(data.msg);
                    }
                }).catch(function(err){
                    //console.log(err)
                    alert('更新失败，请刷新页面后重试');
                });
                //alert('客户确认拒收'+dialog);
            }else{
                //alert('客户取消拒收'+dialog);
            }*/
           /* BaseFactory.rejectExpress(uid,code).then(function(data){
                if(data.code === 0){
                    alert('更新成功');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                //console.log(err)
                alert('更新失败，请刷新页面后重试');
            });*/

        }

    }
]);
//换货页面
app.controller('ExchangeGoodsCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        $scope.loadmore = {more:true};
        $scope.tasks = [] ;
        var page = 1 ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        var uid = $User.get('id');
        $scope.init =function(page){
            //获取任务首页的各个分类的数量
            BaseFactory.exchangeGoods(uid,page,PAGE_SIZE).then(function(data){
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init(page);
        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        }
        $scope.bookTime = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    { text: '取消' },
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function(e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code,$scope.data.booktime.getTime()).then(function(data){
                                    if(data.code === 0){
                                        alert('预约完成');
                                        $scope.tasks.splice(task,1);
                                    }else{
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            })
        }
        //完成派送
        $scope.finishExpress = function(event,code,task){
            //完成派送，记录完成派送时间，更新状态status=9000
            if(!confirm("确认完成派送？")){
                return ;
            }
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.finishExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    //alert('派送完成');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                console.log(err)
            });
        };
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };
        //拒收
        $scope.reject = function(event,code,task){
            //用户拒收，修改订单状态为拒收status=9001
            //alert('用户拒收，该功能尚未开发');
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            var dialog = prompt('确认客户拒收？');
            if(dialog){
                BaseFactory.rejectExpress(uid,code,dialog).then(function(data){
                    if(data.code === 0){
                        alert('更新成功');
                        $scope.tasks.splice(task,1);
                    }else{
                        alert(data.msg);
                    }
                }).catch(function(err){
                    //console.log(err)
                    alert('更新失败，请刷新页面后重试');
                });
                //alert('客户确认拒收'+dialog);
            }else{
                //alert('客户取消拒收'+dialog);
            }
        }

    }
]);
//已完成页面
app.controller('HasFinishedCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init() ;
        };
        //用户id
        var uid = $User.get('id') ;
        $scope.summary = {count:0,amount:0}
        $scope.tasks = [];
        $scope.init =function(){
            //获取任务首页的各个分类的数量
            BaseFactory.hasFinished(uid).then(function(data){
                $scope.summary = {count:data.count,amount:data.sum};
                $scope.tasks = data.list ;
                //$scope.tasks = data ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init();

        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };

        $scope.accountNow = function(tasks){

            if($scope.summary.count === 0 || $scope.tasks.length<1){
                alert("没有要交账数据");
                return;
            }
            //提交当前所有的未结订单，修改is_account=1，主管确认后需要将所有任务的is_account设置为2
            var task_ids = [] ;
            if(confirm('交账后将无法修改，确认交账？')){
                for(var i in tasks){
                    task_ids.push(tasks[i].code);
                }
                $cordovaGeolocation
                    .getCurrentPosition(posOptions)
                    .then(function (position) {
                        lat  = position.coords.latitude;
                        long = position.coords.longitude;
                        BaseFactory.sync(uid,{latitude:lat,longitude:long});
                    }, function(err) {
                        // error
                    });
                BaseFactory.accountNow(uid).then(function(data){
                    if(data.code === 0){
                        $scope.tasks.splice(0);
                        $scope.summary = {count:0,amount:0}
                        alert('成功交账，等待主管确认');
                    }else{
                        alert('出了点问题，请及时联系主管处理');
                    }
                }).catch(function(err){
                    alert('出了点问题，请及时联系主管处理');
                });
            }
        }
    }
]);
//预约页面
app.controller('BookTimeCtrl',['$scope','$state','$stateParams','BaseFactory','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$User,$cordovaGeolocation){
        $scope.loadmore = {more:true};
        $scope.summary = {count:0,amount:0}
        $scope.tasks = [] ;
        var page = 1 ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        var uid = $User.get('id') ;
        $scope.init =function(page){
            //获取任务首页的各个分类的数量
            BaseFactory.booktimeList(uid,page,PAGE_SIZE).then(function(data){
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init(page);
        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        }
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };

        $scope.restartExpress = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            BaseFactory.restartExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    alert('重新开始派送成功');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
            }).catch(function(err){
                console.log(err)
            });
        }

    }
]);
//拒收页面
app.controller('RejectListCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        $scope.loadmore = {more:true};
        $scope.tasks = [] ;
        var page = 1 ;
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        var lat  = 0 ;
        var long = 0 ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.tasks = [] ;
            page = 1 ;
            $scope.init(page) ;
        };
        //用户id
        var uid = $User.get('id') ;
        $scope.init =function(page){
            //获取任务首页的各个分类的数量
            BaseFactory.rejectList(uid,page,PAGE_SIZE).then(function(data){
                console.log(data)
                var count = data.count ;
                if(page >= getPage(count)){
                    $scope.loadmore.more = false
                }
                $scope.tasks = $scope.tasks.concat(data.rows) ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init(page);
        $scope.getMore = function(){
            page++ ;
            $scope.init(page);
        }
        //跳转到任务详情
        $scope.gotoDetail = function(event,code){
            $state.go('tab.taskDetail',{code:code}) ;
        };

        $scope.restartExpress = function(event,code,task){
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long}).then(function(){
                        //alert('定位成功')
                    });
                }, function(err) {
                    // error
                });
            BaseFactory.restartExpress(uid,code).then(function(data){
                if(data.code === 0){
                    //完成派送成功，
                    alert('重新开始派送成功');
                    $scope.tasks.splice(task,1);
                }else{
                    alert(data.msg);
                }
                console.log(data)
            }).catch(function(err){
                console.log(err)
            });
        }

        $scope.bookTime = function(event,code,task) {
            $cordovaGeolocation
                .getCurrentPosition(posOptions)
                .then(function (position) {
                    lat  = position.coords.latitude;
                    long = position.coords.longitude;
                    BaseFactory.sync(uid,{latitude:lat,longitude:long});
                }, function(err) {
                    // error
                });
            $scope.data = {}
            $ionicPopup.show({
                template: '<input type="datetime-local" ng-model="data.booktime">',
                title: '预约时间',
                subTitle: '请选择用户预约的送货时间',
                scope: $scope,
                buttons: [
                    {text: '取消'},
                    {
                        text: '<b>保存</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            if (!$scope.data.booktime) {
                                //don't allow the user to close unless he enters wifi password
                                alert('请输入预约时间')
                                e.preventDefault();
                            } else {
                                BaseFactory.bookTime(uid,code, $scope.data.booktime.getTime()).then(function (data) {
                                    if (data.code === 0) {
                                        alert('预约完成');
                                        $scope.tasks.splice(task, 1);
                                    } else {
                                        alert('预约失败');
                                    }
                                })
                                //return $scope.data.booktime;
                            }
                        }
                    },
                ]
            })
        }

    }
]);

//待领取任务页面
app.controller('WaitTakeCtrl',['$scope','$state','$stateParams','BaseFactory','$ionicPopup','$User','$cordovaGeolocation',
    function($scope,$state,$stateParams,BaseFactory,$ionicPopup,$User,$cordovaGeolocation){
        $scope.tasks = [] ;
        $scope.wait = {waittake:0,dsd:0,sd:0};
        //用户id
        var uid = $User.get('id') ;
        $scope.init =function(){
            BaseFactory.waitList(uid).then(function(data){
                console.log(data)
                $scope.tasks = data;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }

        $scope.initwait =function(){
            BaseFactory.taskWaitTake(uid).then(function(data){
                var waittake = data[0].waittake ||0;
                var dsd = data[0].dsd ||0;
                var sd = data[0].sd ||0;
                $scope.wait = {waittake:waittake,dsd:dsd,sd:sd};
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示列表
        $scope.init();

        $scope.initwait();
    }
]);

app.controller('MissionTest',['$scope','$state','$stateParams','BaseFactory',
    function($scope,$state,$stateParams,BaseFactory) {
        $scope.test = function(){
            BaseFactory.test().then(function(data){
                console.log(data)
            }).catch(function(err){
                console.log(err)
            });
        }
    }
]);
